<template>
  <a-tree-select
    :name="name"
    v-model:value="modelValue"
    tree-data-simple-mode
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :tree-data="treeData"
    @change="updateValue"
    :placeholder="placeholder || '请选择'"
    :load-data="onLoadData"
  />
</template>

<script lang="ts" setup>
import { each } from 'lodash-es'
import { reactive, ref } from 'vue'
import api from '../api'
import dict from '../config/dict'
import type { TreeSelectProps } from 'ant-design-vue'
interface Props {
  name?: string
  placeholder?: string
  modelValue?: any
}
const emit = defineEmits(['update:modelValue'])
const props = defineProps<Props>()
const { name, modelValue, placeholder } = reactive(props)
const treeData = ref<TreeSelectProps['treeData']>([])
api.getDictListByCode(dict.dict165).then((res) => {
  each(res.data.data, (item) => {
    treeData.value?.push({
      id: item.dictCode,
      pId: dict.dict165,
      value: item.dictCode,
      title: item.dictName,
      level: 1,
    })
  })
})

const onLoadData = (treeNode: any): Promise<any> => {
  return api.getDictListByCode(treeNode.id).then((res) => {
    each(res.data.data, (item) => {
      treeData.value?.push({
        id: item.dictCode,
        pId: treeNode.id,
        value: item.dictCode,
        title: item.dictName,
        level: treeNode.level + 1,
        isLeaf: treeNode.level >= 2,
      })
    })
  })
}

function updateValue(value: any): void {
  emit('update:modelValue', value)
}
</script>
